#!/bin/bash

#redis
if [ -d redis ];then
    rm -fr redis
fi

mkdir redis
ports=(6379 6479 6579 6679 7379 7479 7579 7679)
for port in ${ports[*]}
do
    #echo $port
    mkdir -p redis/$port/data
    touch redis/$port/redis.conf
    chmod 777 redis/$port/redis.conf

    tee redis/$port/redis.conf << EOF
    loglevel debug
    appendonly no
    auto-aof-rewrite-percentage 100
    auto-aof-rewrite-min-size 1mb
    client-output-buffer-limit normal 0 0 0
    repl-backlog-size 100mb
    rdbcompression no
    # Generated by CONFIG REWRITE
    notify-keyspace-events "$E"
    min-slaves-to-write 0
    protected-mode no
    dir "/data"
EOF
    if [ $port == 7479 ];then
        echo "slaveof 172.19.0.14 6379" >> redis/$port/redis.conf
    fi
    if [ $port == 6479 ];then
        echo "slaveof 172.19.0.10 6379" >> redis/$port/redis.conf
    fi
done

#vars
DOCKER_ID=${1:-'ctripcorpxpipe'}
DOCKER_TAG=${2:-'1.0'}
XPIPE_MODE=${3:-'console-proxy'}
DOCKER_FILE=docker-compose.yml

if [ -f $DOCKER_FILE ];then
    rm -fr $DOCKER_FILE
fi

if [ $XPIPE_MODE == 'console' ];then
  echo "console mode"
  curl -sSL https://raw.githubusercontent.com/ctripcorp/x-pipe/master/redis/dockerPackage/docker-compose-console.yml > $DOCKER_FILE
elif [ $XPIPE_MODE == 'console-checker' ];then
  echo "console-checker mode "
  curl -sSL https://raw.githubusercontent.com/ctripcorp/x-pipe/master/redis/dockerPackage/docker-compose-console-checker.yml > $DOCKER_FILE
elif [ $XPIPE_MODE == 'console-proxy'  ]; then
  echo "console-proxy mode"
  curl -sSL https://raw.githubusercontent.com/ctripcorp/x-pipe/master/redis/dockerPackage/docker-compose-console-proxy.yml > $DOCKER_FILE
fi

if [ $DOCKER_ID != 'ctripcorpxpipe' ];then
  lines=(`grep -n "ctripcorpxpipe" $DOCKER_FILE | awk -F: '{ print $1 }' | tr '\n' ','` )
  lines=(`echo $lines | tr ',' ' '` )

  for line in ${lines[@]:1}
  do
    sed -i.bak  ''"$line"'s#ctripcorpxpipe#'"$DOCKER_ID"'#' $DOCKER_FILE
  done
fi

if [ $DOCKER_TAG != '1.0' ];then
  sed -i.bak "s#:1.0#:$DOCKER_TAG#g" $DOCKER_FILE
fi
rm $DOCKER_FILE.bak

docker-compose up -d --no-recreate
